<?php
namespace app\api\controller;

use app\api\Controller;
use think\Db;
use app\api\Base;
use think\Exception;
/**
 * 公共上传控制器类
 * 继承了图片，文件上传方法 包括一些业务逻辑的处理
 * 图片上传本地，七牛云，execl上传试题等
 */
class Upload extends Base
{
	/**
     * 文件上传本地
     */
    public function upload()
    {
    	$msg = ['code'=>400, 'msg'=>'上传失败', 'data'=>[]];
        $file = $this->request->file('file');
        $path = ROOT_PATH . 'public/tmp/uploads/';
        $info = $file->move($path);
        if (!$info) {
        	$msg['msg'] = $file->getError();
            return json_encode($msg);
        }
        $data = $this->request->root() . '/tmp/uploads/' . $info->getSaveName();
        $insert = [
            'cate'     => 3,
            'name'     => $data,
            'original' => $info->getInfo('name'),
            'domain'   => '',
            'type'     => $info->getInfo('type'),
            'size'     => $info->getInfo('size'),
            'mtime'    => time(),
        ];
        Db::name('File')->insert($insert);

        $msg['code'] = 200;
        $msg['msg']= '上传成功';
        $msg['data'] = $data;

        return json_encode($msg);
    }

    /**
     * 文件上传到七牛云
     */
    public function qiniuUploadfile()
    {
    	$msg = ['code'=>400, 'msg'=>'上传到七牛云失败', 'data'=>[]];
        $result = \Qiniu::instance()->upload();//七牛上传
        $url=config("qiniu.QINIU_DOMAIN").$result[0]['key'];
        $insert = [
            'cate'     => 3,
            'name'     => $url,
            'original' => $result[0]['name'],
            'domain'   => config("qiniu.QINIU_DOMAIN"),
            'type'     => $result[0]['type'],
            'size'     => $result[0]['size'],
            'mtime'    => time(),
        ];
       // $id= Db::name('file')->insert($insert);
       // if($id){
       		$msg['code'] = 200;
       		$msg['msg'] = "上传成功";
       		$msg['data'] = ['url'=>$url, 'name'=>$result[0]['name']]; # , 'id'=>$id
       // }
       return json_encode($msg);
    }

    /**
     * 试题导入
     * 第一步：先上传到本地
     * @return [type] [description]
     */
	public function uploadexcel1()
    {
    	$msg = ['code'=>400, 'msg'=>'上传execl失败' , 'data'=>[]];
        $_answer = null;
        $_answerData = NULL; 
        $file = $this->request->file('file'); 
        $fileinfo = $file->getInfo();
        $path = ROOT_PATH.'public/tmp/uploads/';
        $info = $file->move($path, $fileinfo['name']);
        $url = './tmp/uploads/' . $info->getSaveName(); 
       
        if($url){
        	$msg['code'] = 200;
        	$msg['msg'] = '上传成功';
        	$msg['data'] = ['url'=>$url];
        }	
		return json_encode($msg);
	}
	/**
	 * 试题导入
     * 第二步：解析数据
     * @return [type] [description]
     */ 
	public function uploadexcel2()
    {
    	$msg = ['code'=>400, 'msg'=>'导入试题失败，请检查execl格式是否有特殊字符', 'data'=>[]];

        $url = $this->request->param('url'); # 试题url
        // $url = "./tmp/uploads/bianzhun.xlsx";
        $qbankId = $this->request->param('qbank_id'); # 题库id
        $admin_reg = $this->request->param('reg'); # admin_reg
        $sectionid = $this->request->param('sectionid'); # 章节

        // $childId = $this->request->param('section_id'); # 如果为子分享题库 

        # 试题表
        # 1：题库qbank_id 2:如果为分享字体库qbank_pid=0 3:上级试题pid
		if(!$url){
			$msg['msg']  = '请上传一个execl';
			return json_encode($msg);
			// return 'not execl file! please load execl.';
		}

        // 通过文件上传，然后取到上传后的完整路径文件名
        // 解析 Excel 头部信息，返回 $excelHeader = ['A' => '第一行A列描述', 'B' => '第一行B列描述', 'C' => '第一行C列描述',...]
		try{ 

	        $excelHeader = \Excel::parseHeader($url);
	        // 将 $excelHeader 数据抛给前端，让用户选择对应关系，然后再返回给后台进行对应数据的解析，例如抛给后台的数据如下isdelete selectnumber describe status level answer
	        # A:题型 B:题干 C:四个选项 D:选项数量 E:大写答案ABC F：解析 G：知识点 H:启用状态 I：题目难度
	        $header = ['A' => 'typeId', 'B' => 'question', 'C' => 'select', 'D' => 'selectNumber', 'E' => 'answer', 'F' => 'describe','G'=>'knowsName','H'=>'status','I'=>'level'];
			 $qbankCount = 0;

			 # 开启事物一个错误全部回滚
			 Db::startTrans();
			 try{
		         $result = \Excel::parse($url, $header, 20, function ($data) {
		         	// var_dump($data);die;

	                # 可以在此处对数据进行过滤处理，例如： 
	                foreach ($data as &$v) {

	                    if ($v['question']=='' || $v['typeId']==''){
	                        continue;
	                    }
	                    if ($v['describe']=='')$v['describe'] = ' ';
	 
	                    $_select = \app\common\logic\DrawQuestion::exAnswerStrToArr($v['select']);	 

	                    if ($v['typeid']==3 && empty($v['select'])) {
	                    	$v['select'] = 'A.正确 B.错误';
	                    }
	                    if(empty($v['select'])){
	                    	$v['select'] = "暂无选项";
	                    }

	                    $v['answer'] = trim($v['answer'])?trim($v['answer']):"暂无答案";//trim(str_replace(',', '', $v['answer']));
	                    if(empty($v['answer'])){
	                    	$v['answer'] = "暂无答案";
	                    }
	                    if($v['status']==1){
	                    	$v['status'] = 1;
	                    }
	                    if($v['status']==2){
	                    	$v['status'] = 0;
	                    }
	                    if($v['status']==3){
	                    	$v['status'] = 2;
	                    }
	                    
	                    $v['level'] = $v['level'];
	                    $v['admin_reg'] = $this->request->param('reg')?$this->request->param('reg'):"0";
	                    $v['qbankId'] = $this->request->param('qbank_id')?$this->request->param('qbank_id'):"0";
	                    $v['sectionId'] = $this->request->param('sectionid')?$this->request->param('sectionid'):"0";
	                    # 如果没有选择知识点默认选中第一个章节
	                    if(empty($v['sectionId'])){
	                    	$defaultSectionId = Db::name('sections')->where(['qbankId'=>$this->request->param('qbank_id'),'isdelete'=>0])->field('id')->find();
	                    	$v['sectionId'] = !empty($defaultSectionId['id'])?$defaultSectionId['id']:"0";
	                    }
	                    $v['createTime'] = time();
	                    $v['knowsName'] = !empty($v['knowsName'])?$v['knowsName']:"未选择知识点";
	                    $qid = Db::name('questions')->insert($v, FALSE, TRUE);
	                    if($v['typeId']==1 || $v['typeId']==2 || $v['typeId']==3){
	                    	$answerFormat = '';
		                    foreach ($_select as $kw => $aw) {
		                        $_answerData[] = array(
		                            'questionsId' => $qid,
		                            'option' => $kw ? $kw : 'UNKOWN',
		                            'answer' => $aw ? $aw : 'UNKOWN'
		                        );
								//处理答案选项为标准格式
								$answerFormat .= $kw < count($_select) ? $kw.'.'.trim($aw).' ' : $kw.'.'.trim($aw);													
		                    }
		                    // var_dump($_answerData);	
	                    }
	                }
	                if(is_array($_select)){
	                	Db::name('QuestionsAnswer')->insertAll($_answerData);	
	                } 
	                
	            }); 
		        # 查询题库试题数量 
		        // ,'status' => 1
		        $ques = Db::table('agk_questions')->where(['admin_reg'=>['in',$admin_reg], 'isdelete' => 0,'qbankId'=>$qbankId])->field('count(*) as num')->find();
		        if (empty($ques['num'])) $ques['num'] = 0; 

		        # 修改题库题目数量
		        Db::table('agk_qbank')->where('id', $qbankId)->update(['total' => $ques['num']]);
		        $qbankCount = $qbankCount ? $qbankCount : 0;
		        $msg['code'] = 200;
		        $msg['msg'] = "导入试题成功";
		        // 提交事务
                Db::commit();

			}catch(Exception $ex){
				# 回滚直接报错
				// $msg['msg'] = $ex->getMessage();
				$msg['msg'] = "提示：导入试题失败，请依照模板认真检查execl格式!";
				Db::rollback();
				$msg['code'] = 400;
				
				return json_encode($msg);
			}

	    }catch(Exception $e){
	    	// $msg['msg'] = $e->getMessage();
	    	$msg['msg'] = "导入试题失败，请依照模板认真检查execl格式!";
	    	Db::rollback();
	    	
	    }

        return json_encode($msg);
    }
}